package com.sojson.util.security.springsecurity.service.impl;

import java.io.IOException;
import java.util.HashSet;
import java.util.Set;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Lazy;
import org.springframework.stereotype.Service;

import com.sojson.entity.po.Member;
import com.sojson.service.MenuService;
import com.sojson.service.RoleService;
import com.sojson.util.security.springsecurity.service.PermissionService;
import com.sojson.util.token.TokenUtil;

/**
 * 权限Service
 * 
 * @author liu
 * @date 2021-04-14
 */
@Service
public class PermissionServiceImpl implements PermissionService {

    @Autowired
    private PermissionServiceImpl permissionServiceImpl;
    @Lazy
    @Autowired
    private RoleService roleService;
    @Lazy
    @Autowired
    private MenuService menuService;

    /**
     * 获取角色列表
     *
     * @param member 用户信息
     * @return
     */
    @Override
    public Set<String> getRolePermission(Member member) {
        Set<String> roles = new HashSet<>();
        Integer id = member.getId();
        // 管理员拥有所有权限
        if (TokenUtil.isAdmin(id)) {
            roles.add(AnnotationServiceOnline.SUPER_ADMIN);
        } else {
            roles.addAll(roleService.getRolePermissionByUserId(id));
        }
        return roles;
    }

    /**
     * 获取权限列表
     *
     * @param member 用户信息
     * @return
     * @throws IOException 
     */
    @Override
    public Set<String> getMenuPermission(Member member) throws IOException {
        return permissionServiceImpl.getMenuPermission(member, TokenUtil.isAdmin(member.getId()));
    }

    /**
     * 获取权限列表
     *
     * @param member    用户信息
     * @param roles     角色信息
     * @return
     * @throws IOException 
     */
    @Override
    public Set<String> getMenuPermission(Member member, Set<String> roles) throws IOException {
        return permissionServiceImpl.getMenuPermission(member,
            TokenUtil.isAdmin(member.getId()) || TokenUtil.isCommon(roles));
    }

    /**
     * 获取权限列表
     * 
     * @param member    用户信息
     * @param isAdmin   是否是管理员
     * @return
     * @throws IOException
     */
    public Set<String> getMenuPermission(Member member, boolean isAdmin) throws IOException {
        Set<String> perms = new HashSet<>();
        Integer id = member.getId();
        // 管理员拥有所有权限
        if (isAdmin) {
            perms.add(AnnotationServiceOnline.ALL_PERMISSION);
        } else {
            perms.addAll(menuService.getMenuPermsByUserId(id));
        }
        return perms;
    }

}